import pandas as pd
from prompt import *
from base import *
from conf import *

def perform_eval(df,qwen_client):
    print('ready')
    rows = []
    for row in df.to_dict(orient='records'):
        print(row)
        q = row['q']
        d = {'q': q}
        variables = {
            'user_labels': "{'职业类型'：['自由职业/创业者']},'学历背景':['硕士'],'毕业年限':['5-10年'],'考研目的':[‘职称’],'考研跳转':['经济压力']}"}
        d['人设'] = variables['user_labels']
        for v in  ['v1','v2','v3','v4']:
            reply = row[v]
            d[v+'答案'] = reply
            messages  =[  {"role": "system", "content": '你是一个专业的问答质量评估助手。'},
                       # {"role": "assistant", "content": start},
                        {"role": "user", "content": score_prompt2.format(question=q,reply=reply)}
                    ]
            a1 = qwen_chat(qwen_client,QwenModel.model,messages)
            # 打分
            d[v + '打分' ] = a1
            print(a1)
        rows.append(d)

    df = pd.DataFrame(rows)
    df.to_excel('新提示词0522_评估.xlsx')


def convert_into_dict(md):
    # Split the markdown into lines
    if isinstance(md,str) is False:
        print('md',md)
        return []
    lines = md.split('\n')
    # Find the start and end of the table
    table_start = None
    table_end = None
    for i, line in enumerate(lines):
        if line.startswith('|') and '---' in line and table_start is None:
            table_start = i + 1  # The line after the header separator
        elif table_start is not None and not line.startswith('|'):
            table_end = i
            break
    # Extract the table rows
    table_rows = []
    for line in lines[table_start:table_end]:
        if line.startswith('|'):
            # Remove leading/trailing | and strip whitespace
            cells = [cell.strip() for cell in line[1:-1].split('|')]
            table_rows.append(cells)
    # Convert to dictionary
    result = []
    for row in table_rows:
        if len(row) >= 3:  # Ensure we have all three columns
            dimension = row[0]
            score = int(row[1]) if row[1].isdigit() else row[1]
            comment = row[2]
            result.append({
                '评估维度': dimension,
                '得分': score,
                '评语': comment
            })
    return result

df = pd.read_excel('新提示词0522_评估.xlsx')
print(df.columns)
def get_version_scores(df):
    """计算每个版本的分数"""
    for c in df.columns:
        if '打分' in c:
            df['tmp'] = df[c].apply(convert_into_dict)
            df[c+'_总分'] = df['tmp'].apply(lambda x:sum(e['得分'] for e in x ))

    for c in df.columns:
        if '_总分' in c:
            print(c,df[c].mean())
    #df.to_excel('打分.xlsx')

def get_dimension_scores(df):
    """
    计算每个维度的分数
    :param df:
    :return:
    """
    rows = []
    for c in df.columns:
        if '打分' in c and '_总分' not in c:
            row = {'版本':c}
            df['tmp'] = df[c].apply(convert_into_dict)

            for dim in dims:
                df[c+dim+'_总分'] = df['tmp'].apply(lambda x:sum(e['得分'] for e in x  if e['评估维度']==dim))
                print(c,dim, df[c+dim+'_总分'].mean())
                row[dim] =  df[c+dim+'_总分'].mean()
            rows.append(row)
    df = pd.DataFrame(rows)
    df.to_excel('总结分数.xlsx')


if __name__ == '__main__':
    qwen_client = get_client(QwenModel)
    #doubao_client = get_client(Doubao)
    #ds_client = get_client(DS)
    df = pd.read_excel('新提示词0522.xlsx')
    perform_eval(df,qwen_client)

    # 总结分数
    get_version_scores(df)
    samples = [
        {'评估维度': '专业准确性', '得分': 4, '评语': '数据引用准确，但未注明来源；政策解读较为清晰。'},
        {'评估维度': '逻辑结构性', '得分': 4, '评语': '结构较清晰，但层次略显单一，缺乏递进式分析。'},
        {'评估维度': '情感支持力', '得分': 3, '评语': '情感表达模板化，共情不足，激励稍显泛泛。'},
        {'评估维度': '对话引导力', '得分': 2, '评语': '缺乏开放性问题和互动设计，引导性较弱。'},
        {'评估维度': '方案适配度', '得分': 3, '评语': '提及方法但未结合用户具体背景，适配度一般。'},
        {'评估维度': '技术整合度', '得分': 3, '评语': '提到"知识图谱+智能督学"但未深入说明技术细节。'},
        {'评估维度': '用户画像应用', '得分': 1, '评语': '未使用任何已知用户信息，画像应用几乎空白。'},
        {'评估维度': '激励有效性', '得分': 3, '评语': '肯定用户优势但路径建议不够具体，激励效果有限。'}
    ]
    dims = [e['评估维度'] for e in samples]
    get_dimension_scores(df)